
#include "base64.h"
#include "process.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <vector>
#include <pthread.h>
#include <algorithm>
#include <map>
#include "CommandParameters.h"
#include <cmath>

void releasePort(int port)
{
  std::string command = "fuser -k " + std::to_string(port) + "/tcp";
  int result = std::system(command.c_str());

  if (result == 0)
  {
    std::cout << "Port " << port << " released successfully." << std::endl;
  }
  else
  {
    std::cerr << "Failed to release port " << port << "." << std::endl;
  }
}


void Socket10000()
{
  int res;
  do
  {
    // 创建Socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
      logMessage("socket failed: ");
      exit(0);
    }

    // 1.准备通讯地址（必须是服务器的）
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    // 将一个无符号短整型的主机数值转换为网络字节顺序，即大尾顺序(big-endian)
    addr.sin_port = htons(Upper_Computer_Port);
    // addr.sin_addr.s_addr = inet_addr("192.168.2.101"); //
    // net_addr方法可以转化字符串，主要用来将一个十进制的数转化为二进制的数，用途多于ipv4的IP转化。
    addr.sin_addr.s_addr = INADDR_ANY;
    // inet_pton(AF_INET, "10.168.3.108", &addr.sin_addr.s_addr);

    // 2.bind()绑定
    // 参数一：0的返回值（socket_fd）
    // 参数二：(struct sockaddr*)&addr 前面结构体，即地址
    // 参数三: addr结构体的长度

    do
    {
      res = bind(socket_fd, (struct sockaddr *)&addr, sizeof(addr));
      if (res == -1)
      {
        logMessage("bind failed: ");
        releasePort(Upper_Computer_Port);
        sleep(5);
      }
      else
      {
        logMessage("bind: " + std::to_string(Upper_Computer_Port) + " success");
        std::cout << "bind: " << Upper_Computer_Port << " success" << std::endl;
      }
    } while (res == -1);

    // 3.监听客户端listen()函数
    // 参数二：进程上限，一般小于30
    listen(socket_fd, 128);
    // 4. 阻塞等待并接受客户端连接
    struct sockaddr_in cliaddr;
    socklen_t clilen = sizeof(cliaddr);
    do
    {
      Upper_Computer_fd = accept(socket_fd, (struct sockaddr *)&cliaddr, &clilen);
      if (Upper_Computer_fd == -1)
      {
        logMessage("accept failed: ");
      }
    } while (Upper_Computer_fd == -1);

    // 打印客户端的地址信息
    char ip[24] = {0};
    printf("客户端的IP地址: %s, 端口: %d\n",
           inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, ip, sizeof(ip)),
           ntohs(cliaddr.sin_port));

    std::string JsonString1 = "已连接";
    std::vector<uint8_t> encodedData1 = EncodeMessage(0x10a1, JsonString1);
    send(Upper_Computer_fd, encodedData1.data(), encodedData1.size(), 0);

    std::vector<uint8_t> EncodedData;
    bool SubcontractingFlag = false;
    int dataLength = 0;
    while (true)
    {
      char buffer[2048];
      memset(buffer, 0, sizeof(buffer));
      ssize_t bytesReceived;
      bytesReceived = read(Upper_Computer_fd, buffer, sizeof(buffer));

      if (bytesReceived > 0)
      {

        // 将接收到的数据添加到ReceivedDataBufferUpper
        ReceivedDataBufferUpper.insert(ReceivedDataBufferUpper.end(), buffer, buffer + bytesReceived);

        std::vector<Message> messages = DecodeMessage(ReceivedDataBufferUpper);
        for (auto message : messages)
        {
          MessageProcessor(message);
        }
      }
      else if (bytesReceived == 0)
      {
        logMessage("Client disconnected...");
        break;
      }
      else
      {
        logMessage("Client read...");
        perror("read");
        break;
      }
    }

    IsServerStart = false;
    close(Upper_Computer_fd);
    close(socket_fd);
  } while (true);
}
